<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card
        :bordered="false"
        style="height: 850px"
        v-if="!importHistoryModal"
      >
        <div class="mb-4 flex items-center justify-between">
          <div>
            <a-form layout="inline">
              <a-form-item label="收费期">
                <a-date-picker
                  v-model:value="value1"
                  picker="year"
                  value-format="YYYY"
                  allowClear
                />
              </a-form-item>
              <a-form-item label="状态">
                <a-select
                  v-model:value="searchStatus"
                  placeholder="请选择"
                  style="width: 120px"
                >
                  <!-- 0 审批中 1 同意 2拒绝 -->
                  <a-select-option value="0">审批中</a-select-option>
                  <a-select-option value="1">同意</a-select-option>
                  <a-select-option value="2">拒绝</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  @click="getTableData"
                  :icon="h(SearchOutlined)"
                  >搜索</a-button
                >
              </a-form-item>
            </a-form>
          </div>
          <div>
            <a-button
              type="primary"
              class="ml-1 mr-1"
              :icon="h(PlusOutlined)"
              @click="addSeason"
              >新增</a-button
            >
            <a-button
              type="primary"
              class="ml-1 mr-1"
              :icon="h(CloudDownloadOutlined)"
              @click="downloadExcel"
            >
              批量导出
            </a-button>
            <!--  0导入 1导出  -->
            <a-button
              class="ml-1 mr-1"
              :icon="h(CloudDownloadOutlined)"
              @click="ExportHistory(1)"
            >
              导出历史
            </a-button>
            <a-button
              class="ml-1 mr-1"
              type="primary"
              :icon="h(CloudUploadOutlined)"
              @click="ImportHistory"
            >
              批量导入
            </a-button>
            <a-button
              class="ml-1 mr-1"
              :icon="h(CloudDownloadOutlined)"
              @click="ExportHistory(0)"
            >
              导入历史
            </a-button>
          </div>
        </div>
        <a-table
          class="ant-table-striped"
          size="middle"
          :columns="columns"
          :data-source="tableData"
          bordered
          :row-class-name="
            (_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
          "
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: 3000, y: 550 }"
          style="width: 1300px"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.dataIndex === 'active'">
              <a-button type="link" @click="handleEdit(record)">修改</a-button>
              <a-popconfirm
                title="确定删除该条数据吗？"
                ok-text="删除"
                cancel-text="取消"
                @confirm="confirm(record)"
                @cancel="cancel"
                placement="bottom"
              >
                <a-button type="link">删除</a-button>
              </a-popconfirm>
              <a-button type="link" @click="onEdit(record)">操作记录</a-button>
            </div>
          </template>
          <template #summary v-if="tableData.length > 0">
            <a-table-summary>
              <a-table-summary-row class="summary-row">
                <a-table-summary-cell :index="0" colspan="4"
                  >合计</a-table-summary-cell
                >
                <a-table-summary-cell :index="1" align="center">{{
                  sumData.sumFullHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="2" align="center">{{
                  sumData.sumFullArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="3" align="center">{{
                  sumData.sumFullMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="8" align="center">{{
                  sumData.sumBaseHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="9" align="center">{{
                  sumData.sumBaseArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="10" align="center">{{
                  sumData.sumBaseMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="11" align="center">{{
                  sumData.sumAllReceivableHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="12" align="center">{{
                  sumData.sumAllReceivableArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="13" align="center">{{
                  sumData.sumAllReceivableMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="14" align="center">{{
                  sumData.sumBeforeReceivableHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="15" align="center">{{
                  sumData.sumBeforeReceivableArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="16" align="center">{{
                  sumData.sumBeforeReceivableMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="17" align="center">{{
                  sumData.sumNowReceivableHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="18" align="center">{{
                  sumData.sumNowReceivableArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="19" align="center">{{
                  sumData.sumNowReceivableMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="20" align="center">{{
                  sumData.sumBeforeDifferenceReceivableHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="21" align="center">{{
                  sumData.sumBeforeDifferenceReceivableArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="22" align="center">{{
                  sumData.sumBeforeDifferenceReceivableMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="23" align="center">{{
                  sumData.sumNowDifferenceReceivableHouses
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="24" align="center">{{
                  sumData.sumNowDifferenceReceivableArea
                }}</a-table-summary-cell>
                <a-table-summary-cell :index="25" align="center">{{
                  sumData.sumNowDifferenceReceivableMoney
                }}</a-table-summary-cell>
                <a-table-summary-cell
                  :index="26"
                  colspan="4"
                ></a-table-summary-cell>
              </a-table-summary-row>
            </a-table-summary>
          </template>
        </a-table>
      </a-card>
    </div>
    <!-- 新增编辑抽屉 -->
    <seasonDrawer
      :open="isDrawerOpen"
      @close="isDrawerOpen = false"
      :data="seasonData"
      :type="drawerType"
    />
    <!-- 操作记录 -->
    <recordDrawer
      :open="isRecordDrawer"
      @close="isRecordDrawer = false"
      :data="rowId"
    />
    <!-- 导出||导入  历史弹框 -->
    <exportHistoryDrawer
      :open="exportHistoryModal"
      :data="exportData"
    ></exportHistoryDrawer>
    <!-- 批量导入页面 -->
    <importHistoryDrawer
      v-if="importHistoryModal"
      @closeDrawer="handleClick"
    ></importHistoryDrawer>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, h, watch, computed, toRaw } from 'vue';
import seasonDrawer from './seasonDrawer.vue';
import recordDrawer from './recordDrawer.vue';
import exportHistoryDrawer from './exportHistoryDrawer.vue';
import importHistoryDrawer from './importHistoryDrawer.vue';
import * as XLSX from 'xlsx';
import {
  getPlanList,
  getSumPlan,
  submitDeleteExamine,
  exportFile,
  getExcelHistory,
} from '#/api/core/heatingSeason';
import { message } from 'ant-design-vue';
import {
  SearchOutlined,
  PlusOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons-vue';
// 日期
const value1 = ref(new Date().getFullYear().toString());
// 审批类型 0 审批中 1 同意 2拒绝
const searchStatus = ref('');
// 默认分页
const current = ref(1); // 当前页码
const total = ref(0); // 总条数
const pageSize = ref(10); // 每页条数
// 表格数据
const tableData = ref([]);
// 是否打开抽屉
const isDrawerOpen = ref(false);
// 接收父页面发请求的参数
const tableDataKey = ref([]);
const tableDataType = ref('');
const tableDataInfo = ref('');
const props = defineProps({
  Keys: {
    type: Array,
    default: () => [],
  },
  Type: {
    type: String,
    default: '',
  },
  Info: {
    type: Array,
    default: () => [],
  },
});
// 表格数据
watch(
  () => [props.Keys, props.Type, props.Info, isDrawerOpen.value],
  ([newKeys, newType, newInfo]) => {
    tableDataKey.value = newKeys; // 把选中的小区存起来
    tableDataType.value = newType;
    tableDataInfo.value = newInfo;
    if (!isDrawerOpen.value) {
      getTableData();
    }
    console.log('接收父组件传来的数据', newKeys, newType, newInfo);
    console.log('关闭抽屉', isDrawerOpen.value);
  },
);

// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
}));
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  console.log('分页参数', pag);
  current.value = pag.current;
  pageSize.value = pag.pageSize;
  getTableData();
};
// 新增弹框
const drawerType = ref(''); // 新增还是编辑
const seasonData = ref({}); // 新增或编辑的数据
const addSeason = () => {
  isDrawerOpen.value = true;
  drawerType.value = 'add';
  if (tableDataInfo.value.length == 0) {
    message.warning('请先选择小区');
  } else if (tableDataInfo.value.length > 1) {
    message.warning('请选择一个小区');
  } else {
    seasonData.value = toRaw(tableDataInfo.value[0]);
  }
};
// 编辑弹窗
const handleEdit = (record: any) => {
  isDrawerOpen.value = true;
  seasonData.value = record;
  drawerType.value = 'edit';
};
// 删除
const confirm = async (record: any) => {
  let res = await submitDeleteExamine(record.id);
  if (res.data.code === 200) {
    message.success(res.data.msg);
    getTableData();
  } else {
    message.error(res.data.msg);
  }
};
const cancel = () => {
  message.success('取消删除');
};
// 记录弹窗
const isRecordDrawer = ref(false);
const rowId = ref();
const onEdit = (record: any) => {
  rowId.value = record.id;
  isRecordDrawer.value = true;
};
// 添加合计计算
type SumData = {
  sumFullHouses: number;
  sumFullArea: number;
  sumFullMoney: number;
  sumBaseHouses: number;
  sumBaseArea: number;
  sumBaseMoney: number;
  sumAllReceivableHouses: number;
  sumAllReceivableArea: number;
  sumAllReceivableMoney: number;
  sumBeforeReceivableHouses: number;
  sumBeforeReceivableArea: number;
  sumBeforeReceivableMoney: number;
  sumNowReceivableHouses: number;
  sumNowReceivableArea: number;
  sumNowReceivableMoney: number;
  sumBeforeDifferenceReceivableHouses: number;
  sumBeforeDifferenceReceivableArea: number;
  sumBeforeDifferenceReceivableMoney: number;
  sumNowDifferenceReceivableHouses: number;
  sumNowDifferenceReceivableArea: number;
  sumNowDifferenceReceivableMoney: number;
};
const sumData = ref<SumData>({});
// 获取表格数据
const columns = [
  {
    title: '小区名称',
    dataIndex: 'villageName',
    key: 'villageName',
    align: 'center',
    width: 200,
  },
  {
    title: '小区类型',
    dataIndex: 'villageType',
    key: 'villageType',
    align: 'center',
    width: 100,
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
    width: 200,
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
    width: 100,
  },
  {
    title: '计划应收全费',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'rcvbFullHouses',
        key: 'rcvbFullHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'rcvbFullArea',
        key: 'rcvbFullArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'rcvbFullMoney',
        key: 'rcvbFullMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '计划应收基本费',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'rcvbBaseHouses',
        key: 'rcvbBaseHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'rcvbBaseArea',
        key: 'rcvbBaseArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'rcvbBaseMoney',
        key: 'rcvbBaseMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '计划应收合计(全费+基本费)',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'allReceivableHouses',
        key: 'allReceivableHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'allReceivableArea',
        key: 'allReceivableArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'allReceivableMoney',
        key: 'allReceivableMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '上一采暖季实收合计(全费+基本费)',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'beforeReceivableHouses',
        key: 'beforeReceivableHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'beforeReceivableArea',
        key: 'beforeReceivableArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'beforeReceivableMoney',
        key: 'beforeReceivableMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '本期采暖季实收合计(全费+基本费)',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'nowReceivableHouses',
        key: 'nowReceivableHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'nowReceivableArea',
        key: 'nowReceivableArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'nowReceivableMoney',
        key: 'nowReceivableMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '计划-上一采暖季实收合计差额',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'beforeDifferenceReceivableHouses',
        key: 'beforeDifferenceReceivableHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'beforeDifferenceReceivableArea',
        key: 'beforeDifferenceReceivableArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'beforeDifferenceReceivableMoney',
        key: 'beforeDifferenceReceivableMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '计划-本期采暖季实收合计差额',
    children: [
      {
        title: '户数(户)',
        dataIndex: 'nowDifferenceReceivableHouses',
        key: 'nowDifferenceReceivableHouses',
        align: 'center',
        width: 100,
      },
      {
        title: '面积(㎡)',
        dataIndex: 'nowDifferenceReceivableArea',
        key: 'nowDifferenceReceivableArea',
        align: 'center',
        width: 100,
      },
      {
        title: '金额(元)',
        dataIndex: 'nowDifferenceReceivableMoney',
        key: 'nowDifferenceReceivableMoney',
        align: 'center',
        width: 100,
      },
    ],
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    width: 100,
    // 当前行的值，当前行数据，行索引  审批状态 0审批中 1同意 2拒绝
    customRender: (text, record, index) =>
      text.record.status === 0
        ? '审批中'
        : text.record.status === 1
          ? '同意'
          : '拒绝',
  },
  {
    title: '修改人',
    dataIndex: 'createPersonName',
    key: 'createPersonName',
    align: 'center',
    width: 150,
  },
  {
    title: '修改时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 200,
  },
  {
    title: '操作',
    dataIndex: 'active', // 这里的 dataIndex 必须和 dataSource 中的 key 一致
    key: 'active', // 这里的 key 必须和 dataSource 中的 key 一致
    width: 250,
    align: 'center',
    fixed: 'right',
  },
];
const getTableData = async () => {
  let data = {
    year: value1.value,
    status: searchStatus.value,
    page: current.value,
    limit: pageSize.value,
  };
  if (tableDataType.value == '热站') {
    (data.isVillageOrHeatExchange = 1),
      (data.heatExchangeIds =
        tableDataKey.value.length == 0 ? null : tableDataKey.value.join(',')),
      getPlanList(data).then((res) => {
        console.log('热站', res);
        tableData.value = res.data.data;
        total.value = res.data.total;
        if (res.length > 0) {
          // 成功之后请求合计的接口
          getSumPlan(data).then((res) => {
            sumData.value = res;
          });
        }
      });
  } else if (tableDataType.value == '小区') {
    (data.isVillageOrHeatExchange = 0),
      (data.villageIds =
        tableDataKey.value.length == 0 ? null : tableDataKey.value.join(',')),
      getPlanList(data).then((res) => {
        console.log('小区1111111111111111', res);
        tableData.value = res.data.data;
        total.value = res.data.total;
        if (res.length > 0) {
          // 成功之后请求合计的接口
          getSumPlan(data).then((res) => {
            sumData.value = res;
          });
        }
      });
  }
};

// 导出
// 使用查询接口实现导出功能
const downloadExcel = async () => {
  let data = {
    year: value1.value,
    status: searchStatus.value,
  };
  if (tableDataType.value == '热站') {
    (data.isVillageOrHeatExchange = 1),
      (data.heatExchangeIds =
        tableDataKey.value.length == 0 ? null : tableDataKey.value.join(',')),
      exportFile(data).then((res) => {
        console.log('热站', res.data.msg);
        if (res.data.code == 200) {
          message.success(res.data.msg);
        } else {
          message.error(res.data.msg);
        }
      });
  } else if (tableDataType.value == '小区') {
    (data.isVillageOrHeatExchange = 0),
      (data.villageIds =
        tableDataKey.value.length == 0 ? null : tableDataKey.value.join(',')),
      exportFile(data).then((res) => {
        console.log('小区1111111111111111', res.data.msg);
        if (res.data.code == 200) {
          message.success(res.data.msg);
        } else {
          message.error(res.data.msg);
        }
      });
  }
};
// 导出历史  //  导入历史
const exportHistoryModal = ref(false);
const exportData = ref([]);
const ExportHistory = async (type) => {
  // Integer type 0导入 1导出 ,Integer page,Integer limit
  let data = {
    type: type,
    page: 1,
    limit: 9999,
  };
  let res = await getExcelHistory(data);
  exportHistoryModal.value = true;
  exportData.value = res.data;
  console.log('导出历史', res);
};
// 导入

const importHistoryModal = ref(false);
const ImportHistory = () => {
  importHistoryModal.value = true;
};
// 关闭导入页面
const handleClick = (data) => {
  importHistoryModal.value = data;
};
</script>
<style scoped>
:deep(.ant-table-summary) {
  background: #fafafa;
  font-weight: bold;
}
</style>
